package test.dom;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLReaderDOM {

    public static void main(String[] args) {
        try {
            // 创建DocumentBuilderFactory实例
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // 使用DocumentBuilderFactory创建DocumentBuilder对象
            DocumentBuilder builder = factory.newDocumentBuilder();
            String path = XMLReaderDOM.class.getClassLoader().getResource("网易手机各地行情.xml").getPath();

            // 使用DocumentBuilder解析XML文件
            Document document = builder.parse(path); // 替换为你的XML文件路径
            // 获取根元素
            Element rootElement = document.getDocumentElement();
            // 打印根元素的名字（PhoneInfo）
            System.out.println("Root Element: " + rootElement.getNodeName());
            // 递归遍历所有节点
            printNode(rootElement, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void printNode(Node node, int depth) {
        // 打印节点及其属性
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // 生成缩进
            String indent = new String(new char[depth * 2]).replace("\0", " ");
            System.out.println(indent + "Element: " + node.getNodeName());
            if (node.hasAttributes()) {
                node.getAttributes().getLength();
                for (int i = 0; i < node.getAttributes().getLength(); i++) {
                    Node attr = node.getAttributes().item(i);
                    System.out.println(indent + "  Attribute: " + attr.getNodeName() + " = " + attr.getNodeValue());
                }
            }
        }

        // 如果节点包含文本内容，则打印
        if (node.hasChildNodes()) {
            NodeList children = node.getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                Node child = children.item(i);
                if (child.getNodeType() == Node.TEXT_NODE && !child.getNodeValue().trim().isEmpty()) {
                    String indent = new String(new char[(depth + 1) * 2]).replace("\0", " ");
                    System.out.println(indent + "Content: " + child.getNodeValue());
                } else if (child.getNodeType() == Node.CDATA_SECTION_NODE) {
                    String indent = new String(new char[(depth + 1) * 2]).replace("\0", " ");
                    System.out.println(indent + "CDATA Section: " + child.getNodeValue());
                }
                // 递归遍历子节点
                printNode(child, depth + 1);
            }
        }
    }
}

